<template>
  <div class="soubg">
    <div class="sou">
      <span> <router-link to="/">首页</router-link></span>
      <span class="fr">
        <span class="fl" v-if="token==null"
          >你好，请<router-link to="/login">登录</router-link>
          &nbsp;
          <router-link to="/regist" style="color: #ff4e00">免费注册</router-link
          >&nbsp;
        </span>
        <span class="fl" v-if="token!=null"
          >欢迎您：<router-link to="/login">{{user.userName}}</router-link>
          &nbsp;<a href="#" @click.prevent="logout()">注销</a>
          &nbsp;
          <router-link v-if="user.type == 1" to="/managerIndex/managerMyself"
            >后台管理</router-link
          >
        </span>
        <span v-if="token != null"><router-link to="/updateUser" style="color: #ff4e00">个人信息</router-link></span>
        <span class="fl">|&nbsp;关注我们：</span>
        <span class="s_sh"
          ><a href="#" class="sh1">新浪</a
          ><a href="#" class="sh2">微信</a></span
        >
        <span class="fr"
          >|&nbsp;<a href="#"
            >手机版&nbsp;<img
              src="http://192.168.1.146:8088/s_tel.png"
              align="absmiddle" /></a
        ></span>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: "pageHead",
  computed: {
    token(){
      return sessionStorage.getItem("token") || null;
    },
    user(){
      try {
        // 当token存在时才解析user
        if (this.token) {
          const userData = sessionStorage.getItem("user");
          return userData ? JSON.parse(userData) : null;
        }
        return null;
      } catch (e) {
        console.error("解析用户数据失败", e);
        return null;
      }
    },
  },
  created(){
    window.addEventListener("storage", this.handleStorageChange);
  },
  methods:{
    handleStorageChange(event) {
      if (event.key === "token" || event.key === "user") {
        this.$forceUpdate();
      }
    },
    logout() {
      if (confirm("确认注销吗？")) {
        window.sessionStorage.removeItem("token");
        window.sessionStorage.removeItem("user");
        alert("注销成功");
        if (this.$router.currentRoute.path !== "/") {
          this.$router.push("/");
        }
      }
    },refreshToken() {
      console.log("正在刷新token...");
      this.token=sessionStorage.getItem("token") || null;
    },
  }, 
};
</script>

<style></style>
